<template>
  <div>
    <div class="projectList">
      <h3 class="title" @click="getProjectList">{{ $t("project.title") }}</h3>
      <!-- @selection-change="getAboutTaskList" -->
      <div class="search">
        <el-input
          class="input-with-select"
          :placeholder="$t('project.search.placeholder')"
          v-model="queryInfo.query_text"
        >
          <el-select
            v-model="queryInfo.query_type"
            slot="prepend"
            style="width: 140px"
          >
            <el-option
              v-for="item in $t('project.options')"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <el-button type="primary" @click="searchProject">{{
          $t("project.search.searchBtn")
        }}</el-button>
        <el-button type="info" plain @click="resetSearch">{{
          $t("project.search.resetBtn")
        }}</el-button>
        <el-button
          type="success"
          plain
          icon="el-icon-circle-plus-outline"
          style="width: 300px"
          @click="createdProject()"
          >{{ $t("project.search.projectCreated") }}</el-button
        >
      </div>
      <el-tabs v-model="queryInfo.project_type" @tab-click="handleClick">
        <el-tab-pane label="scrapyd" name="1"></el-tab-pane>
        <el-tab-pane label="python" name="2"></el-tab-pane>
        <el-tab-pane label="other" name="3"></el-tab-pane>
      </el-tabs>
      <el-table
        v-loading="loading"
        element-loading-text="Loading...."
        :data="projectList"
        border
        @selection-change="getSelectedProject"
        ref="projectList"
        style="margin-top: -14px; min-height: 600px"
      >
        <!-- 下拉关联任务列表 -->
        <!-- <el-table-column type="expand" style="border: 1px solid red">
          <template slot-scope="scope">
            项目下 关联任务
             项目下 关联爬虫
            <div
              class="aboutTaskList"
              v-if="scope.row.reptileChildren.length != 0"
            >
              <h3 class="aboutReptileTitle">关联爬虫</h3>
              <div class="aboutReptileContent">
                <el-table
                  :data="scope.row.reptileChildren"
                  border
                  width="100%"
                  ref="reptileListRef"
                  @selection-change="getSelectedReptile"
                >
                  <el-table-column
                    type="index"
                    width="50"
                    label="序号"
                  ></el-table-column>
                  <el-table-column type="selection" width="55">
                  </el-table-column>
                  <el-table-column
                    prop="en_name"
                    label="名称"
                    width="180"
                    sortable
                  >
                  </el-table-column>
                  <el-table-column prop="description" label="描述" width="180">
                  </el-table-column>
                  <el-table-column
                    prop="state"
                    label="状态"
                    width="80"
                    sortable
                  >
                    <template slot-scope="scope">
                      <el-button
                        v-if="scope.row.state"
                        type="text"
                        style="color: #f56c6c"
                        >停止</el-button
                      >
                      <el-button v-if="!scope.row.state" type="text"
                        >启动</el-button
                      >
                    </template>
                  </el-table-column>
                  <el-table-column prop="warning" label="告警" sortable>
                  </el-table-column>
                  <el-table-column
                    prop="warningDetail"
                    label="告警详情"
                    sortable
                  >
                    <template slot-scope="scope">
                      <span v-if="scope.row.warning == '否'">无...</span>
                      <span v-if="scope.row.warning == '是'">{{
                        scope.row.warningDetail
                      }}</span>
                    </template>
                  </el-table-column>
                </el-table>
                <el-button
                  class="taskStart"
                  type="primary"
                  size="small"
                  plain
                  @click="selectedReptileStart"
                  >批量开启爬虫</el-button
                >
              </div>
            </div>
            <div style="width: 100%; padding-left: 20px" v-else>
              暂无关联爬虫...
            </div>
          </template>
        </el-table-column> -->
        <!-- <el-table-column type="selection" width="55"> </el-table-column> -->
        <el-table-column
          type="index"
          width="61"
          :label="$t('project.table.index')"
          :index="table_index"
        ></el-table-column>
        <el-table-column
          prop="name"
          :label="$t('project.table.name')"
          show-overflow-tooltip
          sortable
        >
          <!-- <template slot-scope="{ row }">
              <el-button type="text">参数配置</el-button>
            </template> -->
        </el-table-column>
        <el-table-column
          prop="client.ip"
          show-overflow-tooltip
          :label="$t('project.table.hostIP')"
        >
        </el-table-column>
        <el-table-column
          prop="description"
          show-overflow-tooltip
          :label="$t('project.table.descript')"
        >
        </el-table-column>

        <!-- <el-table-column prop="state" label="状态" width="80" sortable>
          <template slot-scope="scope">
            <el-button
              v-show="scope.row.state"
              type="text"
              style="font-size: 20px; padding: 0; color: #67c23a"
              icon="el-icon-video-pause"
            ></el-button>
            <el-button
              v-show="!scope.row.state"
              style="font-size: 20px; padding: 0; color: #f56c6c; margin: 0"
              type="text"
              icon="el-icon-video-play"
            ></el-button>
          </template>
        </el-table-column> -->
        <el-table-column
          prop="reptileChildren.length"
          :label="$t('project.table.reptileNum')"
          sortable
        >
        </el-table-column>
        <el-table-column
          prop="taskChildren.length"
          :label="$t('project.table.taskNum')"
          sortable
        >
        </el-table-column>
        <el-table-column
          prop="item_count"
          v-if="queryInfo.project_type == 1"
          :label="$t('project.table.dataNum')"
          sortable
        >
        </el-table-column>
        <el-table-column
          :label="$t('project.table.deployment_time')"
          prop="built_at"
          width="110"
          align="center"
        >
        </el-table-column>
        <!-- <el-table-column
          prop="log"
          :label="$t('project.table.analysis_diagram')"
        >
          <template slot-scope="scope">
            <el-button type="text" @click="findLog(scope)">{{
              $t("project.btn.analysis_diagram")
            }}</el-button>
          </template>
        </el-table-column> -->
        <el-table-column
          :label="$t('project.table.deploy')"
          width="90"
          v-if="queryInfo.project_type == 1"
          key="1"
        >
          <template slot-scope="scope">
            <el-popconfirm
              v-loading.fullscreen.lock="fullscreenLoading"
              element-loading-background="rgba(0, 0, 0, 0.4)"
              element-loading-text="Loading...."
              :title="$t('project.btn.deploySure')"
              @confirm="deployBtn(scope.row)"
              :confirm-button-text="$t('project.btn.sure')"
              :cancel-button-text="$t('project.btn.cancel')"
            >
              <el-button slot="reference" type="text">{{
                $t("project.table.deploy")
              }}</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>

        <el-table-column :label="$t('project.table.operation')" width="380">
          <template slot-scope="scope">
            <!-- git -->
            <el-button
              v-show="scope.row.type == 1"
              type="success"
              slot="reference"
              icon="el-icon-share"
              size="mini"
              plain
              @click="configureGit(scope.row)"
              style="margin: 0 10px 10px 0"
              >{{ $t("project.btn.git") }}</el-button
            >
            <!-- 数据库配置 -->
            <el-button
              type="success"
              slot="reference"
              icon="el-icon-coin"
              size="mini"
              plain
              @click="databaseConfig(scope.row)"
              style="margin: 0 10px 10px 0"
              >{{ $t("project.btn.database") }}</el-button
            >
            <!-- <el-button
              v-show="scope.row.type == 2"
              type="success"
              slot="reference"
              icon="el-icon-share"
              size="mini"
              plain
              @click="configureRelease(scope.row)"
              >{{ $t("project.btn.release") }}</el-button
            > -->
            <!-- 同步爬虫 -->
            <!-- <el-popconfirm
              :title="$t('project.message.sure')"
              @confirm="tongbu(scope)"
            >
              <el-button
                v-show="scope.row.type == 1"
                type="primary"
                slot="reference"
                icon="el-icon-s-ticket"
                size="mini"
                plain
                style="margin: 0 10px 10px 0"
                >{{ $t("project.btn.tongbu") }}</el-button
              >
            </el-popconfirm> -->

            <!-- 编辑 -->
            <el-button
              style="margin: 0 10px 10px 0"
              type="warning"
              icon="el-icon-edit"
              size="mini"
              plain
              @click="projectEditor(scope.row.id)"
              >{{ $t("project.btn.editor") }}</el-button
            >
            <!-- 批量创建任务 -->
            <el-popconfirm
              :title="$t('project.message.sure')"
              @confirm="piliang(scope)"
            >
              <el-button
                v-show="scope.row.type == 1"
                type="primary"
                slot="reference"
                icon="el-icon-s-unfold "
                size="mini"
                plain
                style="margin: 0 10px 10px 0"
                >{{ $t("project.btn.piliang") }}</el-button
              >
            </el-popconfirm>
            <!-- 删除 -->
            <el-popconfirm
              :title="$t('project.btn.del_msg')"
              @confirm="delProject(scope)"
            >
              <el-button
                style="margin: 0 10px 10px 0"
                type="danger"
                slot="reference"
                icon="el-icon-delete"
                size="mini"
                plain
                >{{ $t("project.btn.delete") }}</el-button
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="projectFooter">
      <!-- <el-button size="mini" type="primary" @click="selectedProjectStart"
        >批量开启项目</el-button
      > -->
      <el-pagination
        class="pagination"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.page"
        :page-size="queryInfo.pagesize"
        layout="total, prev, pager, next, jumper"
        :total="AllList.total"
      >
      </el-pagination>
    </div>
    <!-- 项目编辑对话框 -->
    <ProjectEditorDialog
      :projectList="projectList"
      :projectEditorId="projectEditorId"
      :hostList="hostList"
      :projectEditorDialogVisible="projectEditorDialogVisible"
      @closeDialog="closeProjectEditor"
    ></ProjectEditorDialog>
    <!-- 打开分析图对话框 -->
    <FindLogDialog
      @closeDialog="findLogDialogVisible = false"
      :analysisData="analysisData"
      :findLogDialogVisible="findLogDialogVisible"
    ></FindLogDialog>
    <!-- 任务编辑对话框 -->
    <!-- <TaskEditorDialog
      :taskList="AllList.task"
      :taskEditorId="taskEditorId"
      :taskEditorDialogVisible="taskEditorDialogVisible"
      @closeDialog="closeTaskEditor"
    ></TaskEditorDialog> -->
    <!-- 新建项目对话框 -->
    <ProjectCreatedDialog
      :projectCreatedDialogVisible="projectCreatedDialogVisible"
      @closeDialog="closeCreatedProject"
    ></ProjectCreatedDialog>
    <!-- 配置git模态框 -->
    <ConfigureGitDialog
      :DialogShow="ConfigureGitDialogShow"
      :form="ConfigureGitRowData"
      @closeDialog="configureGit"
    />
    <!-- 配置项目模态框 -->
    <ProjectConfigurationDialog
      :DialogShow="ProjectConfigurationShow"
      @closeDialog="configureRelease"
      :form="ProjectConfigurationRowData"
    />
    <ProjectDataConfig
      :dataDialogShow="dataDialogShow"
      :row="dataConfigPro"
      @closeDialog="closeDataConfig"
    ></ProjectDataConfig>
  </div>
</template>

<script>
import ProjectEditorDialog from "../../../components/ProjectEditorDialog.vue";
import ProjectCreatedDialog from "../../../components/ProjectCreatedDialog.vue";
import FindLogDialog from "../../../components/FindLogDialog.vue";
import TaskEditorDialog from "../../../components/TaskEditorDialog.vue";
import ConfigureGitDialog from "../../../components/configureGitDialog.vue";
import ProjectConfigurationDialog from "../../../components/ProjectConfigurationDialog.vue";
import ProjectDataConfig from "../../../components/ProjectDataConfig.vue";
import customed from "./customed";
export default {
  components: {
    ProjectEditorDialog,
    FindLogDialog,
    TaskEditorDialog,
    ProjectCreatedDialog,
    ConfigureGitDialog,
    ProjectConfigurationDialog,
    ProjectDataConfig,
  },
  data() {
    return {
      fullscreenLoading: false,
      loading: false,
      activeName: "first",
      // 搜索文字
      searchText: "",
      // 搜索条件
      select: 1,
      // 获取爬虫的参数对象
      queryInfo: {
        // 当前的页数
        page: 1,
        // 当前每页显示多少条数据
        pagesize: 8,
        query_text: "",
        query_type: 1,
        project_type: "1",
      },
      // 控制任务编辑弹框的显示与隐藏
      taskEditorDialogVisible: false,
      // 控制项目日志弹框的显示与隐藏
      findLogDialogVisible: false,
      //  控制项目编辑弹框的显示与隐藏
      projectEditorDialogVisible: false,
      // 控制新建项目弹框显示与隐藏
      projectCreatedDialogVisible: false,
      // 配置git模态框
      ConfigureGitDialogShow: false,
      ConfigureGitRowData: {},
      // 项目配置模态框
      ProjectConfigurationShow: false,
      ProjectConfigurationRowData: {},
      // 打开任务编辑框 传入对应的ID
      projectEditorId: "",
      // 打开项目编辑框 传入对应的ID
      taskEditorId: "",
      // 项目列表
      projectList: [],
      // 选中项目列表
      selectedProjectList: [],
      // 选中任务列表
      selectedTaskList: [],
      // 选中爬虫列表
      selectedReptileList: [],
      // 所有列表单独列出来
      AllList: {},
      // 分析图数据
      analysisData: {},
      // 主机列表
      hostList: [],
      // 数据库配置的显示与隐藏
      dataDialogShow: false,
      dataConfigPro: "",
    };
  },
  created() {
    this.getHostList();
    this.getProjectList();
  },
  methods: {
    tongbu(scope) {
      // 调用全屏加载loading
      const loading = this.$loading({
        lock: true,
        text: this.$t("project.message.crawler_loading"),
        background: "rgba(0, 0, 0, 0.7)",
      });

      this.$http
        .get("/crawler/batch_creat", {
          params: {
            project_name: scope.row.name,
            client_id: scope.row.client.id,
            project_id: scope.row.id,
          },
        })
        .then((res) => {
          console.log(res);
          if (res.data.code != 0) {
            // 关闭loading
            loading.close();
            this.$message.error(this.$t("project.message.crawler_err"));
          } else {
            loading.close();
            this.$message.success(this.$t("project.message.crawler_succ"));
          }
        });
    },
    piliang(scope) {
      const loading = this.$loading({
        lock: true,
        text: this.$t("project.message.task_loading"),
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.$http
        .get("/task/batch_creat", {
          params: { client_id: scope.row.client.id, project_id: scope.row.id },
        })
        .then((res) => {
          if (res.data.code != 0) {
            loading.close();
            this.$message.error(this.$t("project.message.task_err"));
          } else {
            loading.close();
            this.$message.success(this.$t("project.message.task_succ"));
          }
        });
    },
    // tabs 选项卡切换触发函数
    handleClick(tab, event) {
      this.queryInfo.page = 1;
      this.getProjectList();
    },
    // 数据库配置
    databaseConfig(data) {
      this.dataDialogShow = true;
      this.dataConfigPro = data;
    },
    closeDataConfig() {
      this.dataDialogShow = false;
    },
    //配置发布
    configureRelease(data) {
      this.ProjectConfigurationShow = this.ProjectConfigurationShow
        ? false
        : true;
      if (data.id) return (this.ProjectConfigurationRowData = data);
    },
    // 配置git
    configureGit(data) {
      console.log("-----配置git-----", data);
      console.log(typeof data);
      this.ConfigureGitDialogShow = this.ConfigureGitDialogShow ? false : true;
      // if (data != 1) return (this.ConfigureGitRowData = data);
      // this.getProjectList();
      if (data) {
        if (data != 1) {
          this.ConfigureGitRowData = data;
        }
      } else {
        this.getProjectList();
      }
    },
    //一键部署
    deployBtn(data) {
      this.fullscreenLoading = true;
      // this.$message("未开发");
      console.log(data);
      if (!data.address || data.address == "") {
        this.$message.warning(this.$t("project.message.git_address"));
        return;
      }
      if (!data.to_address || data.to_address == "") {
        this.$message.warning(this.$t("project.message.to_address"));
        return;
      }
      // if (!data.deploy_address || data.deploy_address == "") {
      //   this.$message.warning(this.$t("project.message.deploy_address"));
      //   return;
      // }
      this.$http
        .get("/deploy/project", { params: { id: data.id } })
        .then((res) => {
          console.log(res.data.code);
          this.fullscreenLoading = false;
          if (res.data.code == 1) return this.$message.error(res.data.msg);
          this.$message.success(this.$t("project.message.deploy"));
        });
    },
    // 搜索功能
    searchProject() {
      console.log("搜索条件：" + this.select + " 搜索内容：" + this.searchText);
      this.getProjectList();
    },
    // 分页功能
    handleCurrentChange(val) {
      this.queryInfo.page = val;
      this.getProjectList();
    },
    // 获取项目 任务 爬虫列表
    async getProjectList() {
      this.loading = true;

      const { data: res } = await this.$http.get("/project", {
        params: this.queryInfo,
      });
      console.log(res);
      this.AllList = res;
      // 将任务下面的爬虫 转换为任务的属性
      res.task.forEach((val) => {
        let reptile = res.reptiles.filter((ele) => {
          return ele.task_id == val.id + "";
        });
        val.reptileChildren = reptile;
      });
      const { data: res1 } = await this.$http.get("/host");
      // 将项目下面的任务或者爬虫 转换为projectList的children属性
      res.projects.forEach((val) => {
        let reptiles = res.reptiles.filter((ele) => {
          if (!ele.task_id) return ele.project_id == val.id;
        });
        let task = res.task.filter((ele) => {
          return ele.project_id == val.id;
        });

        let host = res1.find((vals) => {
          return vals.id == val.client_id;
        });
        val.client = host;
        val.reptileChildren = reptiles;
        val.taskChildren = task;
      });
      this.projectList = res.projects;
      console.log("----项目列表------", this.projectList);
      this.loading = false;
    },
    async getHostList() {
      const { data: res } = await this.$http.get("/host");
      this.hostList = res;
    },
    // 树形结构
    //  删除项目函数
    delProject(scope) {
      this.$http
        .get("/project/del", { params: { id: scope.row.id } })
        .then((res) => {
          this.$message.success(this.$t("project.message.del_success"));
          this.getProjectList();
        });
      console.log("删除" + scope.row.id + "这个项目");
    },
    // 点击打开分析图按钮
    findLog(scope) {
      console.log(scope.row.id);
      this.$http
        .get("/project/analysis", {
          params: { project_id: scope.row.id },
        })
        .then((res) => {
          if (res.data.data.length) {
            this.analysisData = res.data;
            this.findLogDialogVisible = true;
          } else {
            this.$message.warning(this.$t("project.message.fxt_no_task"));
          }
        })
        .catch(() => {
          this.$message.error(this.$t("project.message.data_err"));
        });
    },
    // 点击项目的编辑按钮
    projectEditor(id) {
      this.projectEditorDialogVisible = true;
      this.projectEditorId = id;
      console.log(id);
    },
    // 获取选中项目列表
    getSelectedProject(val) {
      this.selectedProjectList = val;
    },
    // 新建项目函数
    createdProject() {
      this.projectCreatedDialogVisible = true;
    },
    // 关闭新建项目弹框
    closeCreatedProject(way) {
      this.projectCreatedDialogVisible = false;
      if (way) return;
      this.getProjectList();
    },
    // 批量开启项目
    selectedProjectStart() {
      if (this.selectedProjectList.length == 0)
        return this.$message.warning("请先选择要开启的项目");
      console.log("批量开启项目");
      console.log(this.selectedProjectList.length);
      // 清除表格选中状态
      this.$refs.projectList.clearSelection();
    },
    // 获取选中任务列表
    getSelectedTask(val) {
      this.selectedTaskList = val;
    },
    // 批量开启任务
    selectedTaskStart() {
      if (this.selectedTaskList.length == 0)
        return this.$message.warning("请选择要开启的任务");
      console.log("批量开启任务");
      this.$refs.taskList.clearSelection();
    },
    // 获取选中爬虫列表
    getSelectedReptile(val) {
      this.selectedReptileList = val;
    },
    // 批量开启爬虫
    selectedReptileStart() {
      if (this.selectedReptileList.length == 0)
        return this.$message.warning("请选择要开启的爬虫");
      console.log("批量开启爬虫");
      console.log(this.selectedReptileList);
      this.$refs.reptileListRef.clearSelection();
    },
    // 点击任务编辑按钮
    taskEditor(id) {
      this.taskEditorDialogVisible = true;
      this.taskEditorId = id;
    },
    // 删除任务函数
    delTask(scope) {
      this.$http
        .get("/task/del", { params: { id: scope.row.id } })
        .then((res) => {
          this.$message.success("删除任务成功！");
          this.getProjectList();
        });
      console.log("删除" + scope.row.id + "这个任务");
    },
    // 重置搜索输入框
    resetSearch() {
      this.queryInfo.query_text = "";
      this.queryInfo.query_type = 1;
      this.getProjectList();
    },
    closeProjectEditor(way) {
      this.projectEditorDialogVisible = false;
      if (way) return;
      this.getProjectList();
    },
    closeTaskEditor(way) {
      this.taskEditorDialogVisible = false;
      // 如果点击的取消 那么就不重新请求列表  如果点击的保存 那么重新请求列表刷新数据
      if (way) return;
      this.getProjectList();
    },
    // 解决表格序号分页后不连续的问题
    table_index(index) {
      return (this.queryInfo.page - 1) * this.queryInfo.pagesize + index + 1;
    },
  },
};
</script>

<style lang='less' scoped>
.title {
  color: #606266;
}
.search {
  margin: 10px 0;
  .el-input {
    width: 34%;
  }
  .el-button {
    margin-left: 10px;
  }
}
.aboutTaskList {
  display: flex;
  // flex-wrap: wrap;
  margin-left: 2%;
  margin-bottom: 20px;
  .aboutTaskTitle {
    width: 40px;
    padding: 10px;
    height: 120px;
    border-radius: 20px 0px 0px 60px;
    text-align: center;
    background-color: #ffb7b7;
    color: #606266;
  }
  .aboutReptileTitle {
    width: 40px;
    padding: 10px;
    height: 120px;
    border-radius: 20px 0px 0px 60px;
    text-align: center;
    background-color: #b7c2ff;
    color: #606266;
  }
  .aboutTaskContent {
    width: 97%;
    border: 1px solid #ffb7b7;
    .taskStart {
      margin: 10px;
    }
  }
  .aboutReptileContent {
    width: 97%;
    border: 1px solid #b7c2ff;
    .taskStart {
      margin: 10px;
    }
  }
  .aboutReptileList {
    display: flex;
    margin-left: 2%;
    .aboutReptileTitle {
      width: 40px;
      padding: 10px;
      height: 120px;
      border-radius: 20px 0px 0px 60px;
      text-align: center;
      background-color: #b7c2ff;
      color: #606266;
    }
    .aboutReptileContent {
      // width: 97%;
      border: 1px solid #b7c2ff;
      .reptileStart {
        margin: 10px;
      }
    }
  }
}
.projectFooter {
  display: flex;
  .pagination {
    margin: 15px 0 0 20px;
  }
}
</style>